package cliente.responsehandler.xml;

import cliente.auxiliar.GereErros;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import cliente.domain.User;
import cliente.parsing.XmlParsingUtils;
import cliente.responsehandler.DocumentParseException;
import cliente.responsehandler.NonOkResponseException;

import java.io.IOException;
import java.util.Vector;

/**
 * Handler/Parser for response to requests to URL:
 * http://twitter.com/users/show.xml?screen_name=TWITTER_USERNAME
 */
public class XmlUserFolloingFollowersHandler implements ResponseHandler<Vector<User>> {

    GereErros erro = null;

    public XmlUserFolloingFollowersHandler(GereErros erro) {
        this.erro = erro;
    }

    public Vector<User> handleResponse(HttpResponse httpResponse) throws IOException {

        Vector<User> respUser = new Vector<User>();

        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            System.out.println("Codigo erro:"+httpResponse.getStatusLine().getStatusCode());
            erro.trataErros(httpResponse);
        }
        
        // create the XML pull parser
        XmlPullParser xpp = new MXParser();
        User user = null;

        try {
            xpp.setInput(httpResponse.getEntity().getContent(), null);
            xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);

            // XML document read loop
            int eventType = xpp.getEventType();
            String eventName = xpp.getName();

            while(eventType != XmlPullParser.END_DOCUMENT) {
                //System.out.println("entrei no parse do doc");
                eventType = xpp.next();
                eventName = xpp.getName();
                //System.out.println("Event Name"+eventName);

                if (eventType == XmlPullParser.START_TAG) {
                    if ("user".equals(eventName)) {
                        user = XmlParsingUtils.parseUser(xpp);
                        respUser.add(user);
                    }
                }             
            }
        } catch (XmlPullParserException e) {
            // wrap exception and propagate it upwards
            throw new DocumentParseException(e);
        }

        if (user == null) {
            System.err.println("Warning! Failed to parse XML to create a valid User!");
            // Remember to check in your code if the result of this response handler is not null.
            // When you reach the daily API call limit, Twitter will reply with empty bodies.
            // Another alternative would be to throw an Exception, e.g.: DailyLimitExceededException
        }
        return respUser;
    }
}
